import { BlockEnum } from '@/components/workflow/types'
import { useWorkFlowStore } from '@/store/workflowStore'
import { useEffect, useState } from 'react'
import { findSources } from '../utils'
import { useReactFlow } from 'reactflow';
/**
 * 自动获取关联节点上的可选入参
 */
export const useSourceOptions = (data: any, type:string[]=[]) => {
  const [options, setOptions] = useState([])
  const { selectedNode, flowInstance, flowVariables } = useWorkFlowStore()
  const { getNodes} = useReactFlow()

  const fillIterationParams = (options:any, nodeId:string, isIterationChild:boolean) => {
    const type = flowVariables[nodeId]?.type || ''
    if (isIterationChild) {
      if (type === 'iteration') {
        const inputList = flowVariables[nodeId]?.inputList || []
        if (inputList.length > 0 && inputList[0].valuet) {
          const itemSourceType = inputList[0]?.sourceType?.replace('array_','')
          options.push({
            title: 'iteration',
            label: '当前迭代',
            key: 'iteration',
            options: [
              {
                value: `${nodeId},item`,
                label: 'item',
                sourceType: itemSourceType
              },
              {
                value: `${nodeId},index`,
                label: 'index',
                sourceType: 'number'
              }
            ]
          })
        }
      } else if ( type === 'loop' ) {
        options.push({
          title: 'loop',
          label: '循环',
          key: 'loop',
          options:flowVariables[nodeId]?.inputList
          ?.filter(item => item.variable)
          .map(item => ({
            value: `${nodeId},${item.variable}`,
            label: item.variable,
            sourceType: item.sourceType? item.sourceType : item.type,
          }))
        })
      }
    }
  }
  
  useEffect(() => {
    if (!flowInstance || Object.keys(flowInstance).length === 0) return

    console.log(
      '>>>useSourceOptions：selectedNode.id, data.id',
      selectedNode.id,
      data.id,
      data,
      flowInstance.getEdges(),
      flowVariables
    )

    if (selectedNode.id !== data.id) return

    const node = getNodes().find(node => node.id === data.id)
    const parentNode = getNodes().find(pNode => pNode.id === node?.parentId)
    const edges = flowInstance.getEdges()
    const sources = findSources(data.id, edges).filter((id: string) => flowVariables[id])
    // 如果是迭代节点或者迭代节点的子节点，添加父节点的sources
    const isIterationChild = node?.parentId ? true : false
    const parentSources = isIterationChild ? findSources(node.parentId, edges).filter((id: string) => flowVariables[id])
      : []
    
    const options = []
    fillIterationParams(options, node?.parentId, isIterationChild)
    const curOption = [...sources, ...parentSources].map((id: string) => {
      const optionItem = {
        title: id,
        label: id,
        key: id,
        options: []
      }

      if (flowVariables[id]?.type === BlockEnum.Start) {
        optionItem.options = flowVariables[id]?.variables
          ?.filter(item => item.variable)
          .map(item => ({
            value: `${id},${item.variable}`,
            label: item.variable,
            sourceType: item.type,
          }))
      } else if(flowVariables[id]?.type === BlockEnum.Loop){
        optionItem.options = flowVariables[id]?.inputList
        ?.filter(item => item.variable)
        .map(item => ({
          value: `${id},${item.variable}`,
          label: item.variable,
          sourceType: item.sourceType? item.sourceType : item.type,
        }))
      }else if (
        [BlockEnum.LLM, BlockEnum.KnowledgeRetrieval, BlockEnum.Tool, BlockEnum.Code, BlockEnum.Intend,
          BlockEnum.DocExtractor,BlockEnum.HttpRequest,BlockEnum.TextConcatenation,BlockEnum.VarUpdate,
          BlockEnum.Iteration,BlockEnum.List].includes(flowVariables[id]?.type)
      ) {
        optionItem.options = flowVariables[id]?.outputList
          ?.filter(item => item.variable)
          .map(item => ({
            value: `${id},${item.variable}`,
            label: item.variable,
            sourceType: item.sourceType? item.sourceType : item.type,
          }))
      }

      optionItem.label = flowVariables[id]?.title || id
      return optionItem
    })

    options.push(...curOption)
    const filteredOptions = options.map(option => ({
      ...option,
      options: type.length > 0 ? option.options?.filter(opt => type.includes(opt.sourceType)) : option.options
    })).filter(option => option.options?.length > 0 && !option.title.includes('if-else'));

    console.log('相关sources：sources, curOption', sources, filteredOptions)

    setOptions(filteredOptions)
  }, [selectedNode, flowInstance, flowVariables, data.id])

  return {
    options,
    setOptions
  }
}
